package com.south.base.test.arithmetic;

import org.junit.Assert;
import org.junit.Test;

/**
 * 开平方
 * @author Administrator
 * @date 2020/1/9 9:42
 */
public class Square {
    @Test
    public void square() {
        Assert.assertEquals(Math.sqrt(2), square(2, 0.0000001), 0.0000001);
        Assert.assertEquals(Math.sqrt(3), square(3, 0.0000001), 0.0000001);
        Assert.assertEquals(Math.sqrt(4), square(4, 0.0000001), 0.0000001);
        Assert.assertEquals(Math.sqrt(11), square(11, 0.00000001), 0.00000001);
        Assert.assertEquals(Math.sqrt(16), square(16, 0.0000001), 0.0000001);
    }

    public double square(int n, double accurate) {
        double temp = 1;
        for (double dif = temp - n / temp; abs(dif) > accurate; dif = temp - n / temp) {
            temp = (temp + n / temp) / 2;
        }
        return temp;
    }

    public double abs(double d) {
        return d <= 0.0D ? 0.0D - d : d;
    }
}
